package com.yunchang.springboot.scheduled.mwsfinance;

import com.yunchang.springboot.base.BaseService;
import com.yunchang.springboot.mapper.caravan.CaravanMskuDataMapper;
import com.yunchang.springboot.mapper.finance.FinanceCaravanDebitCreditRelationMapper;
import com.yunchang.springboot.mapper.mwsfinance.FAdjustmentsMapper;
import com.yunchang.springboot.mapper.mwsfinance.FInventoryDailyMapper;
import com.yunchang.springboot.mapper.mwsfinance.FReimbursementMapper;
import com.yunchang.springboot.mapper.mwsreport.MwsDailyInventoryHistoryMapper;
import com.yunchang.springboot.mapper.mwsreport.MwsInventoryAdjustmentsMapper;
import com.yunchang.springboot.mapper.mwsutils.CwfzFinancialSubjectsMapper;
import com.yunchang.springboot.models.mwsfinance.FAdjustments;
import com.yunchang.springboot.models.mwsreportbean.MwsInventoryAdjustments;
import com.yunchang.springboot.utils.DateUtil;
import com.yunchang.springboot.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * 盘库
 */
@Component
@Configuration
@Service
@Slf4j
@EnableScheduling
public class FAdjustmentsScheduled extends BaseService {

    static final String SELL_ABLE = "SELLABLE";

    static final String NORMAL = "normal";

    static final String OTHER = "other";

    static Integer LIMIT_VALUE = 10000;

//    static final List<String> EU_COUNTRY_LIST = Arrays.asList("DE", "FR", "IT", "UK", "ES");

    private List<String> EUROPE_COUNTRY_NAME = Arrays.asList("DE", "UK", "FR", "IT", "ES");

    static final String US = "US";

    static final String CA = "CA";

    static final String MX = "MX";

    static final String JP = "JP";

    static String DOCUMENTS_ID = "PKD";
    /**
     * 出入库明细
     */
    @Autowired
    FInventoryDetailsScheduled fInventoryDetailsScheduled;

    /**
     * 盘库原始数据
     */
    private MwsInventoryAdjustmentsMapper mwsInventoryAdjustmentsMapper;

    @Autowired
    public void setMwsInventoryAdjustmentsMapper(MwsInventoryAdjustmentsMapper mwsInventoryAdjustmentsMapper) {
        this.mwsInventoryAdjustmentsMapper = mwsInventoryAdjustmentsMapper;
    }

    /**
     * 每日库存记录原始数据
     */
    private MwsDailyInventoryHistoryMapper mwsDailyInventoryHistoryMapper;

    @Autowired
    public void setMwsDailyInventoryHistoryMapper(MwsDailyInventoryHistoryMapper mwsDailyInventoryHistoryMapper) {
        this.mwsDailyInventoryHistoryMapper = mwsDailyInventoryHistoryMapper;
    }

    /**
     * 赔偿财务数据
     */
    private FReimbursementMapper fReimbursementMapper;

    @Autowired
    public void setfReimbursementMapper(FReimbursementMapper fReimbursementMapper) {
        this.fReimbursementMapper = fReimbursementMapper;
    }

    /**
     * 获取借贷科目
     */
    private CwfzFinancialSubjectsMapper cwfzFinancialSubjectsMapper;

    @Autowired
    public void setCwfzFinancialSubjectsMapper(CwfzFinancialSubjectsMapper cwfzFinancialSubjectsMapper) {
        this.cwfzFinancialSubjectsMapper = cwfzFinancialSubjectsMapper;
    }

    /**
     * 库存数据
     */
    private FInventoryDailyMapper fInventoryDailyMapper;

    @Autowired
    public void setFInventoryDailyMapper(FInventoryDailyMapper fInventoryDailyMapper) {
        this.fInventoryDailyMapper = fInventoryDailyMapper;
    }

    /**
     * 盘库财务数据
     */
    private FAdjustmentsMapper fAdjustmentsMapper;

    @Autowired
    public void setFAdjustmentsMapper(FAdjustmentsMapper fAdjustmentsMapper) {
        this.fAdjustmentsMapper = fAdjustmentsMapper;
    }

    /**
     * 获取stock_sku
     */
    private CaravanMskuDataMapper caravanMskuDataMapper;

    @Autowired
    public void setCaravanMskuDataMapper(CaravanMskuDataMapper caravanMskuDataMapper) {
        this.caravanMskuDataMapper = caravanMskuDataMapper;
    }

    /**
     * 获取costUnit
     */
    private FinanceCaravanDebitCreditRelationMapper financeCaravanDebitCreditRelationMapper;

    @Autowired
    public void setFinanceCaravanDebitCreditRelationMapper(FinanceCaravanDebitCreditRelationMapper financeCaravanDebitCreditRelationMapper) {
        this.financeCaravanDebitCreditRelationMapper = financeCaravanDebitCreditRelationMapper;
    }


    public void getFAdjustments(String date, List<String> reasonList) {
        List<MwsInventoryAdjustments> mwsInventoryAdjustmentsList = mwsInventoryAdjustmentsMapper.selectByFinanceStatus(1, null, reasonList, date);
        Integer mwsInventoryAdjustmentsListSize = mwsInventoryAdjustmentsList.size();
        int forNum = 1;
        log.info("盘库原始数据的数量为：" + mwsInventoryAdjustmentsListSize);
        if (mwsInventoryAdjustmentsListSize > LIMIT_VALUE) {
            forNum += mwsInventoryAdjustmentsListSize / LIMIT_VALUE;
            for (; forNum > 0; forNum--) {
                log.info("盘库生成财务数据的剩余次数：" + forNum);
                mwsInventoryAdjustmentsList = mwsInventoryAdjustmentsMapper.selectByFinanceStatus(1, LIMIT_VALUE, reasonList, date);
                mwsInventoryAdjustmentsDispose(mwsInventoryAdjustmentsList);
            }
        } else {
            mwsInventoryAdjustmentsDispose(mwsInventoryAdjustmentsList);
        }
    }

    public void mwsInventoryAdjustmentsDispose(List<MwsInventoryAdjustments> mwsInventoryAdjustmentsList) {
        if (null != mwsInventoryAdjustmentsList && !mwsInventoryAdjustmentsList.isEmpty()) {
            List<Object> fAdjustmentsInsertList = new ArrayList<>();
            for (MwsInventoryAdjustments mwsInventoryAdjustments : mwsInventoryAdjustmentsList) {
                FAdjustments fAdjustments = new FAdjustments();
                fAdjustments.setIsAdjustManauly(1);
                fAdjustments.setApprovalStatus(1);
                fAdjustments.setIsInventoryDetails(1);
                fAdjustments.setDocumentsId(DOCUMENTS_ID + UUIDUtil.getUUID());
                String sellerId = mwsInventoryAdjustments.getSellerId();
                fAdjustments.setSellerId(sellerId);
                String fulfillmentCenterId = mwsInventoryAdjustments.getFulfillmentCenterId();
                String area = mwsInventoryAdjustments.getArea();
                String sku = mwsInventoryAdjustments.getSku();
                fAdjustments.setSku(sku);
                String country = null;
                Map<String, String> countryMap = getCountry(sellerId, fulfillmentCenterId, area, sku);
                if (null != countryMap && !countryMap.isEmpty()) {
                    if (countryMap.containsKey("country")) {
                        country = countryMap.get("country");
                    }
                    if (countryMap.containsKey("country2")) {
                        fAdjustments.setCountryStatus(2);
                        country = countryMap.get("country2");
                    }
                }
                fAdjustments.setCountry(country);
                String adjustedDate = mwsInventoryAdjustments.getAdjustedDate();
                fAdjustments.setDate(adjustedDate);
                fAdjustments.setFnsku(mwsInventoryAdjustments.getFnsku());
                fAdjustments.setFulfillmentCenterId(fulfillmentCenterId);
                Integer originalQuantity = mwsInventoryAdjustments.getQuantity();
                fAdjustments.setOriginalQuantity(originalQuantity);
                String reason = mwsInventoryAdjustments.getReason();
                fAdjustments.setReason(reason);
                String disposition = mwsInventoryAdjustments.getDisposition();
                fAdjustments.setDisposition(disposition);
                Integer quantityBy6e = getQuantityBySomething(sellerId, adjustedDate, sku, fulfillmentCenterId, reason);
                fAdjustments.setQuantityBy6e(quantityBy6e);
                Integer quantityBy7hkuq = getQuantityBySomething(sellerId, adjustedDate, sku, fulfillmentCenterId, reason);
                fAdjustments.setQuantityBy7hkuq(quantityBy7hkuq);
                Integer quantityByP = getQuantityBySomething(sellerId, adjustedDate, sku, fulfillmentCenterId, reason);
                fAdjustments.setQuantityByP(quantityByP);
                String type = null;
                Map<String, String> typeMap = getType(reason, disposition, quantityBy6e, quantityBy7hkuq, quantityByP, sellerId, sku, adjustedDate);
                if (typeMap.containsKey(OTHER)) {
                    fAdjustments.setIsAdjustManauly(2);
                    type = typeMap.get(OTHER);
                    fAdjustments.setType(typeMap.get(OTHER));
                }
                if (typeMap.containsKey(NORMAL)) {
                    type = typeMap.get(NORMAL);
                    fAdjustments.setType(typeMap.get(NORMAL));
                }
                Integer quantity = Math.abs(originalQuantity);
                fAdjustments.setQuantity(quantity);
                if (StringUtils.isEmpty(getDebitSubjectId(type))) {
                    fAdjustments.setIsAdjustManauly(2);
                }
                fAdjustments.setDebitSubjectId(getDebitSubjectId(type));
                String creditSubjectId = getCreditSubjectId(type);
                if (StringUtils.isEmpty(creditSubjectId)) {
                    fAdjustments.setIsAdjustManauly(2);
                }
                fAdjustments.setCreditSubjectId(creditSubjectId);
                Double costUnit = 0.0;
                Map<String, Double> costUnitMap = getCostUnit(reason, sellerId, country, sku, creditSubjectId, adjustedDate);
                if (null != costUnitMap && !costUnitMap.isEmpty()) {
                    if (costUnitMap.containsKey("costUnit")) {
                        costUnit = costUnitMap.get("costUnit");
                        fAdjustments.setCostUnit(costUnitMap.get("costUnit"));
                    }
                    if (costUnitMap.containsKey("costUnit3")) {
                        costUnit = costUnitMap.get("costUnit3");
                        fAdjustments.setIsAdjustManauly(3);
                        fAdjustments.setCostUnit(costUnitMap.get("costUnit3"));
                    }
                    if (costUnitMap.containsKey("costUnit4")) {
                        costUnit = costUnitMap.get("costUnit4");
                        fAdjustments.setIsAdjustManauly(4);
                        fAdjustments.setCostUnit(costUnitMap.get("costUnit4"));
                    }
                    if (costUnitMap.containsKey("costUnit5")) {
                        costUnit = costUnitMap.get("costUnit5");
                        fAdjustments.setIsAdjustManauly(5);
                        fAdjustments.setCostUnit(costUnitMap.get("costUnit5"));
                    }
                    if (costUnitMap.containsKey("costUnit6")) {
                        costUnit = costUnitMap.get("costUnit6");
                        fAdjustments.setIsAdjustManauly(6);
                        fAdjustments.setCostUnit(costUnitMap.get("costUnit6"));
                    }
                    fAdjustments.setAmount(new BigDecimal(quantity * costUnit).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                fAdjustments.setCurrency("RMB");
                fAdjustments.setCreateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
                fAdjustments.setUpdateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
                fAdjustmentsInsertList.add(fAdjustments);
                mwsInventoryAdjustments.setFinanceStatus(2);
            }
            try {
                baseInsertList(fAdjustmentsInsertList);
                mwsInventoryAdjustmentsMapper.updateFinanceStatusByMwsInventoryAdjustmentsList(mwsInventoryAdjustmentsList);
                log.info("盘库财务数据已生成");
            } catch (Exception e) {
                log.error("插入数据时出现错误，盘库" + e);
                throw new RuntimeException("插入数据时出现错误，盘库");
            }
        } else {
            log.info("未查询到对应的盘库数据列表，时间为" + DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
        }
    }


    /**
     * @param sellerId
     * @return
     */
    public Map<String, String> getCountry(String sellerId, String fulfillmentCenterId, String area, String sku) {
        if (area.equals(JP)) {
            return new HashMap<String, String>(1) {{
                put("country", JP);
            }};
        }
        if (EUROPE_COUNTRY_NAME.contains(area)) {
            return new HashMap<String, String>(1) {{
                put("country", "EU");
            }};
        }
        if (!StringUtils.isEmpty(fulfillmentCenterId) && !StringUtils.isEmpty(sellerId)) {
            String countryByFulfillmentCenterId = mwsDailyInventoryHistoryMapper.selectCountryBySellerIdAndFulfillmentCenterId(sellerId, fulfillmentCenterId);
            if (!StringUtils.isEmpty(countryByFulfillmentCenterId)) {
                return new HashMap<String, String>(1) {{
                    put("country", countryByFulfillmentCenterId);
                }};
            }
        }
        if (!StringUtils.isEmpty(area) && !StringUtils.isEmpty(sku)) {
            List<String> countryList = mwsDailyInventoryHistoryMapper.selectCountryBySellerIdAndSku(sellerId, sku);
            if (null != countryList && !countryList.isEmpty()) {
                if (countryList.size() == 1) {
                    return new HashMap<String, String>(1) {{
                        put("country", countryList.get(0));
                    }};
                }
                if (countryList.size() > 1) {
                    if (countryList.contains(US)) {
                        return new HashMap<String, String>(1) {{
                            put("country2", US);
                        }};
                    }
                    if (countryList.contains(CA)) {
                        return new HashMap<String, String>(1) {{
                            put("country2", CA);
                        }};
                    }
                    if (countryList.contains(MX)) {
                        return new HashMap<String, String>(1) {{
                            put("country2", MX);
                        }};
                    }
                }
            }
        }
        log.info("获取国家失败,盘库。sellerId: " + sellerId + " fulfillmentCenterId: " + fulfillmentCenterId + " area: " + area + " sku: " + sku);
        return null;
    }

    /**
     * 根据传入的参数获取三个和quantity有关的值
     *
     * @param sellerId
     * @param adjustedDate
     * @param sku
     * @param fulfillmentCenterId
     * @param reason
     * @return
     */
    public Integer getQuantityBySomething(String sellerId, String adjustedDate, String sku, String
            fulfillmentCenterId, String reason) {
        if (StringUtils.isEmpty(sellerId) || StringUtils.isEmpty(adjustedDate) || StringUtils.isEmpty(sku) || StringUtils.isEmpty(fulfillmentCenterId) || StringUtils.isEmpty(reason)) {
            return 0;
        }
        Integer quantity = 0;
        List<String> reasonBy6E = Arrays.asList("6", "E");
        List<String> reasonBy7HKUQ = Arrays.asList("7", "H", "K", "U", "Q");
        List<String> reasonByP = Arrays.asList("P");
        if (reasonBy6E.contains(reason)) {
            quantity = mwsInventoryAdjustmentsMapper.selectSumQuantityBySellerIdAndAdjustedDateAndSkuAndFulfillmentCenterIdAndReasonList(sellerId, adjustedDate.substring(0,10), sku, fulfillmentCenterId, reasonBy6E);
        }
        if (reasonBy7HKUQ.contains(reason)) {
            quantity = mwsInventoryAdjustmentsMapper.selectSumQuantityBySellerIdAndAdjustedDateAndSkuAndFulfillmentCenterIdAndReasonList(sellerId, adjustedDate.substring(0,10), sku, fulfillmentCenterId, reasonBy7HKUQ);
        }
        if (reasonByP.contains(reason)) {
            quantity = mwsInventoryAdjustmentsMapper.selectSumQuantityBySellerIdAndAdjustedDateAndSkuAndFulfillmentCenterIdAndReasonList(sellerId, adjustedDate.substring(0,10), sku, fulfillmentCenterId, reasonByP);
        }
        return quantity;
    }


    /**
     * 获取type
     *
     * @param reason
     * @param disposition
     * @param quantityBy6e
     * @param quantityBy7hkuq
     * @param quantityByP
     * @param sellerId
     * @param sku
     * @param adjustedDate
     * @return
     */
    public Map<String, String> getType(String reason, String disposition, Integer quantityBy6e, Integer
            quantityBy7hkuq, Integer quantityByP, String sellerId, String sku, String adjustedDate) {
        disposition = disposition.toUpperCase();
        switch (reason) {
            case "5":
            case "M":
                if (disposition.equals(SELL_ABLE)) {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "可售丢失");
                    }};
                } else {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "不可售丢失");
                    }};
                }
            case "F":
                if (disposition.equals(SELL_ABLE)) {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "可售找回");
                    }};
                } else {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "不可售找回");
                    }};
                }
            case "3":
                if (disposition.equals(SELL_ABLE)) {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "可售商品重新定义入库");
                    }};
                } else {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "不可售商品重新定义入库");
                    }};
                }
            case "4":
                if (disposition.equals(SELL_ABLE)) {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "可售商品重新定义出库");
                    }};
                } else {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "不可售商品重新定义出库");
                    }};
                }
            case "O":
                if (disposition.equals(SELL_ABLE)) {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "可售商品库存更正出库");
                    }};
                } else {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "不可售商品库存更正出库");
                    }};
                }
            case "D":
                if (disposition.equals(SELL_ABLE)) {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "可售商品盘库弃置");
                    }};
                } else {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "不可售商品盘库弃置");
                    }};
                }
            case "6":
            case "E":
                if (quantityByP.equals(0)) {
                    if (disposition.equals(SELL_ABLE)) {
                        return new HashMap<String, String>(1) {{
                            put(NORMAL, "残损出库");
                        }};
                    } else {
                        return new HashMap<String, String>(1) {{
                            put(NORMAL, "不可售残损出库");
                        }};
                    }
                } else if (quantityBy7hkuq.equals(quantityByP)) {
                    if (disposition.equals(SELL_ABLE)) {
                        return new HashMap<String, String>(1) {{
                            put(NORMAL, "残损出库");
                        }};
                    } else {
                        return new HashMap<String, String>(1) {{
                            put(NORMAL, "不可售残损出库");
                        }};
                    }
                } else if ((quantityBy7hkuq + quantityBy6e) == quantityByP) {
                    if (disposition.equals(SELL_ABLE)) {
                        return new HashMap<String, String>(1) {{
                            put(NORMAL, "残损出库，不可售入库");
                        }};
                    } else {
                        return new HashMap<String, String>(1) {{
                            put(NORMAL, "不可售残损出库，不可售入库");
                        }};
                    }
                } else {
                    if (disposition.equals(SELL_ABLE)) {
                        return new HashMap<String, String>(1) {{
                            put(OTHER, "残损出库");
                        }};
                    } else {
                        return new HashMap<String, String>(1) {{
                            put(OTHER, "不可售残损出库");
                        }};
                    }
                }
            case "7":
            case "H":
            case "K":
            case "U":
            case "Q":
                if (quantityBy7hkuq.equals(quantityByP)) {
                    if (disposition.equals(SELL_ABLE)) {
                        return new HashMap<String, String>(1) {{
                            put(NORMAL, "可售库存属性更改出库");
                        }};
                    } else {
                        return new HashMap<String, String>(1) {{
                            put(NORMAL, "不可售库存属性更改出库");
                        }};
                    }
                } else if ((quantityBy7hkuq + quantityBy6e) == quantityByP) {
                    if (disposition.equals(SELL_ABLE)) {
                        return new HashMap<String, String>(1) {{
                            put(NORMAL, "可售库存属性更改出库");
                        }};
                    } else {
                        return new HashMap<String, String>(1) {{
                            put(NORMAL, "不可售库存属性更改出库");
                        }};
                    }
                } else {
                    if (disposition.equals(SELL_ABLE)) {
                        return new HashMap<String, String>(1) {{
                            put(OTHER, "可售库存属性更改出库");
                        }};
                    } else {
                        return new HashMap<String, String>(1) {{
                            put(OTHER, "不可售库存属性更改出库");
                        }};
                    }
                }
            case "N":
                Integer quantity = mwsInventoryAdjustmentsMapper.selectSumQuantityBySellerIdAndAdjustedDateAndSkuAndReason(sellerId, sku, adjustedDate.substring(0,10), reason);
                Integer quantityReimbursedInventory = fReimbursementMapper.selectSumQuantityReimbursedInventoryBySellerIdAndSkuAndAdjustedDate(sellerId, sku, adjustedDate.substring(0,10));
                if (quantity.equals(quantityReimbursedInventory)) {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "赔偿入库");
                    }};
                } else if (quantityReimbursedInventory.equals(0)) {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "找回");
                    }};
                } else {
                    return new HashMap<String, String>(1) {{
                        put(OTHER, "找回");
                    }};
                }
            case "P":
                if (disposition.equals(SELL_ABLE)) {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "可售库存属性更改入库");
                    }};
                } else {
                    return new HashMap<String, String>(1) {{
                        put(NORMAL, "不可售库存属性更改入库");
                    }};
                }
        }
        return null;
    }

    /**
     * 根据type获取借方科目
     *
     * @param type
     * @return
     */
    public String getDebitSubjectId(String type) {
        if (StringUtils.isEmpty(type)) {
            return "";
        }
        return cwfzFinancialSubjectsMapper.selectDebitSubjectIdByType(type);
    }

    /**
     * 根据type获取贷方科目
     *
     * @param type
     * @return
     */
    public String getCreditSubjectId(String type) {
        if (StringUtils.isEmpty(type)) {
            return "";
        }
        return cwfzFinancialSubjectsMapper.selectCreditSubjectIdByType(type);
    }

    /**
     * @param reason
     * @param sellerId
     * @param country
     * @param sku
     * @param creditSubjectId
     * @param date
     * @return 返回的为map集合，其key为costUnit是正常，其余的costUnit后是多少就需要将isAdjustManauly的值设置为多少
     */
    public Map<String, Double> getCostUnit(String reason, String sellerId, String country, String sku, String
            creditSubjectId, String date) {
        String creditSubjectIdOtherValueOne = "140603";
        String creditSubjectIdOtherValueTwo = "140605";
        List<String> firstReasonList = Arrays.asList("6", "7", "E", "H", "K", "U", "Q", "5", "M", "3");
        String pReason = "P";
        List<String> secondReasonList = Arrays.asList("F", "N");
        List<String> thirdlyReasonList = Arrays.asList("O", "D", "4");
        if (firstReasonList.contains(reason)) {
            Double amount = fInventoryDailyMapper.selectSumAmountBySellerIdAndCountryAndSkuAndCreditSubjectIdAndDate(sellerId, country, sku, creditSubjectId, date.substring(0,10));
            Integer quantity = fInventoryDailyMapper.selectSumQuantityBySellerIdAndCountryAndSkuAndCreditSubjectIdAndDate(sellerId, country, sku, creditSubjectId, date.substring(0,10));
            if (null != amount && null != quantity && amount != 0.0 && quantity != 0) {
                return new HashMap<String, Double>(1) {{
                    put("costUnit", new BigDecimal(amount / quantity).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                }};
            }
            if (creditSubjectId.equals(creditSubjectIdOtherValueOne)) {
                Double amount2 = fInventoryDailyMapper.selectSumAmountBySellerIdAndCountryAndSkuAndCreditSubjectIdAndDate(sellerId, country, sku, creditSubjectIdOtherValueTwo, date.substring(0,10));
                Integer quantity2 = fInventoryDailyMapper.selectSumQuantityBySellerIdAndCountryAndSkuAndCreditSubjectIdAndDate(sellerId, country, sku, creditSubjectIdOtherValueTwo, date.substring(0,10));
                if (null != amount2 && null != quantity2 && amount2 != 0.0 && quantity2 != 0) {
                    return new HashMap<String, Double>(1) {{
                        put("costUnit3", new BigDecimal(amount2 / quantity2).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                    }};
                }
            }
            if (creditSubjectId.equals(creditSubjectIdOtherValueTwo)) {
                Double amount3 = fInventoryDailyMapper.selectSumAmountBySellerIdAndCountryAndSkuAndCreditSubjectIdAndDate(sellerId, country, sku, creditSubjectIdOtherValueOne, date.substring(0,10));
                Integer quantity3 = fInventoryDailyMapper.selectSumQuantityBySellerIdAndCountryAndSkuAndCreditSubjectIdAndDate(sellerId, country, sku, creditSubjectIdOtherValueOne, date.substring(0,10));
                if (null != amount3 && null != quantity3 && amount3 != 0.0 && quantity3 != 0) {
                    return new HashMap<String, Double>(1) {{
                        put("costUnit3", new BigDecimal(amount3 / quantity3).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                    }};
                }
            }
            Map<String, Object> amountAndQuantityMap = fInventoryDailyMapper.selectSumAmountAndSumQuantityBySellerIdAndCountryAndSkuAndWarehouse(sellerId, country, sku, creditSubjectId);
            if (null != amountAndQuantityMap && !amountAndQuantityMap.isEmpty()) {
                if (null != amountAndQuantityMap.get("amount") && null != amountAndQuantityMap.get("quantity")) {
                    Double amount4 = new Double(amountAndQuantityMap.get("amount").toString());
                    Integer quantity4 = new Integer(amountAndQuantityMap.get("quantity").toString());
                    if (null != amount4 && null != quantity4 && amount4 != 0 && quantity4 != 0) {
                        return new HashMap<String, Double>(1) {{
                            put("costUnit4", new BigDecimal(amount4 / quantity4).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                        }};
                    }
                }
            }
            if (reason.equals("3")) {
                String warehouse = "默认仓库";
                String subjectId = "1406";
                String stockSku = getStockSku(sku);
                Map<String, Object> amountAndSkuNumMap = financeCaravanDebitCreditRelationMapper.selectSumSkuNumAndSumAmountByStockSkuAndWarehouseAndSubjectId(stockSku, warehouse, subjectId);
                if (null != amountAndSkuNumMap && null != amountAndSkuNumMap.get("amount") && null != amountAndSkuNumMap.get("skuNum")) {
                    Double amountByFinance = new Double(amountAndSkuNumMap.get("amount").toString());
                    Integer skuNum = new Integer(amountAndSkuNumMap.get("skuNum").toString());
                    if (null != amountByFinance && null != skuNum && amountByFinance != 0 && skuNum != 0) {
                        return new HashMap<String, Double>(1) {{
                            put("costUnit5", new BigDecimal((amountByFinance / skuNum) + 15).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                        }};
                    }
                }
            }
        }
        if (reason.equals(pReason)) {
            List<String> reasonList = Arrays.asList("E", "H", "K", "U", "Q", "6");
            return getCostUnitAndReasonIsPOrFN(sellerId, country, sku, date.substring(0,10), reasonList);
        }
        if (secondReasonList.contains(reason)) {
            List<String> reasonList = Arrays.asList("5", "M");
            return getCostUnitAndReasonIsPOrFN(sellerId, country, sku, date.substring(0,10), reasonList);
        }
        if (thirdlyReasonList.contains(reason)) {
            Double amount = fInventoryDailyMapper.selectSumAmountBySellerIdAndCountryAndSkuAndCreditSubjectIdAndDate(sellerId, country, sku, creditSubjectId, date.substring(0,10));
            Integer quantity = fInventoryDailyMapper.selectSumQuantityBySellerIdAndCountryAndSkuAndCreditSubjectIdAndDate(sellerId, country, sku, creditSubjectId, date.substring(0,10));
            if (null != amount && null != quantity && amount != 0.0 && quantity != 0) {
                return new HashMap<String, Double>(1) {{
                    put("costUnit", new BigDecimal(amount / quantity).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                }};
            }
            Map<String, Object> amountAndQuantityMap = fInventoryDailyMapper.selectSumAmountAndSumQuantityBySellerIdAndCountryAndSkuAndWarehouse(sellerId, country, sku, creditSubjectId);
            if (null != amountAndQuantityMap && !amountAndQuantityMap.isEmpty()) {
                if (null != amountAndQuantityMap.get("amount") && null != amountAndQuantityMap.get("quantity")) {
                    Double amount2 = new Double(amountAndQuantityMap.get("amount").toString());
                    Integer quantity2 = new Integer(amountAndQuantityMap.get("quantity").toString());
                    if (null != amount2 && null != quantity2 && amount2 != 0 && quantity2 != 0) {
                        return new HashMap<String, Double>(1) {{
                            put("costUnit3", new BigDecimal(amount2 / quantity2).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                        }};
                    }
                }
            }
            List<String> warehouseList = Arrays.asList("140603", "140605");
            Map<String, Object> amountAndQuantityMap2 = fInventoryDailyMapper.selectSumAmountAndSumQuantityBySellerIdAndCountryAndSkuAndWarehouseList(sellerId, country, sku, warehouseList);
            if (null != amountAndQuantityMap2 && !amountAndQuantityMap2.isEmpty()) {
                if (null != amountAndQuantityMap2.get("amount") && null != amountAndQuantityMap2.get("quantity")) {
                    Double amount3 = new Double(amountAndQuantityMap2.get("amount").toString());
                    Integer quantity3 = new Integer(amountAndQuantityMap2.get("quantity").toString());
                    if (null != amount3 && null != quantity3 && amount3 != 0 && quantity3 != 0) {
                        return new HashMap<String, Double>(1) {{
                            put("costUnit4", new BigDecimal(amount3 / quantity3).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                        }};
                    }
                }
            }
        }
        log.info("getCostUnit 获取costUnit使用默认值60，盘库生成财务数据。sellerId：" + sellerId + " country：" + country + " sku：" + sku + " creditSubjectId：" + creditSubjectId + " date：" + date + " reason:" + reason);
        // 最后默认返回60
        return new HashMap<String, Double>(1) {{
            put("costUnit6", new BigDecimal(60).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
        }};
    }

    public Map<String, Double> getCostUnitAndReasonIsPOrFN(String sellerId, String country, String sku, String
            date, List<String> reasonList) {
        Double amount = fAdjustmentsMapper.selectSumAmountBySellerIdAndCountryAndSkuAndDateAndReasonList(sellerId, country, sku, date, reasonList);
        Integer quantity = fAdjustmentsMapper.selectSumQuantityBySellerIdAndCountryAndSkuAndDateAndReasonList(sellerId, country, sku, date, reasonList);
        if (null != amount && null != quantity && amount != 0.0 && quantity != 0) {
            return new HashMap<String, Double>(1) {{
                put("costUnit", new BigDecimal(amount / quantity).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
            }};
        }
        Map<String, Object> amountAndQuantityMap = fAdjustmentsMapper.selectSumAmountAndQuantityBySellerIdAndCountryAndSkuAndDateAndReasonList(sellerId, country, sku, reasonList);
        if (null != amountAndQuantityMap && !amountAndQuantityMap.isEmpty()) {
            if (null != amountAndQuantityMap.get("amount") && null != amountAndQuantityMap.get("quantity")) {
                Double amount2 = new Double(amountAndQuantityMap.get("amount").toString());
                Integer quantity2 = new Integer(amountAndQuantityMap.get("quantity").toString());
                if (null != amount2 && null != quantity2 && amount2 != 0 && quantity2 != 0) {
                    return new HashMap<String, Double>(1) {{
                        put("costUnit3", new BigDecimal(amount2 / quantity2).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                    }};
                }
            }
        }
        List<String> warehouseList = Arrays.asList("140603", "140605");
        Map<String, Object> amountAndQuantityMap2 = fInventoryDailyMapper.selectSumAmountAndSumQuantityBySellerIdAndCountryAndSkuAndWarehouseList(sellerId, country, sku, warehouseList);
        if (null != amountAndQuantityMap2 && !amountAndQuantityMap2.isEmpty()) {
            if (null != amountAndQuantityMap2.get("amount") && null != amountAndQuantityMap2.get("quantity")) {
                Double amount3 = new Double(amountAndQuantityMap2.get("amount").toString());
                Integer quantity3 = new Integer(amountAndQuantityMap2.get("quantity").toString());
                if (null != amount3 && null != quantity3 && amount3 != 0 && quantity3 != 0) {
                    return new HashMap<String, Double>(1) {{
                        put("costUnit4", new BigDecimal(amount3 / quantity3).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                    }};
                }
            }
        }
        String warehouse = "默认仓库";
        String subjectId = "1406";
        String stockSku = getStockSku(sku);
        Map<String, Object> amountAndSkuNumMap = financeCaravanDebitCreditRelationMapper.selectSumSkuNumAndSumAmountByStockSkuAndWarehouseAndSubjectId(stockSku, warehouse, subjectId);
        if (null != amountAndSkuNumMap && null != amountAndSkuNumMap.get("amount") && null != amountAndSkuNumMap.get("skuNum")) {
            Double amountByFinance = new Double(amountAndSkuNumMap.get("amount").toString());
            Integer skuNum = new Integer(amountAndSkuNumMap.get("skuNum").toString());
            if (null != amountByFinance && null != skuNum && amountByFinance != 0 && skuNum != 0) {
                return new HashMap<String, Double>(1) {{
                    put("costUnit5", new BigDecimal((amountByFinance / skuNum) + 15).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                }};
            }
        }
        log.info("getCostUnitAndReasonIsPOrFN 获取costUnit使用默认值60，盘库生成财务数据。sellerId：" + sellerId + " country：" + country + " sku：" + sku + " date：" + date + " reasonList: " + reasonList.toString());
        // 最后默认返回60
        return new HashMap<String, Double>(1) {{
            put("costUnit6", new BigDecimal(60).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
        }};
    }

    /**
     * 根据sku获取stockSku
     *
     * @param sku
     * @return
     */
    public String getStockSku(String sku) {
        if (StringUtils.isEmpty(sku)) {
            log.info("根据sku获取stockSku失败，sku为空，盘库生成财务数据");
            return null;
        }
        return caravanMskuDataMapper.getStockSku(sku);
    }
}
